var express = require('express');
var router = express.Router();
var db = require("../util/DataBase.js");

var rankScore = require("../system/article_rank_score.js");

var articleService = require("../service/article.js");
var replyService = require("../service/reply.js");
var messageService = require("../service/message.js");
var searchService = require("../service/search.js");

router.post('/reply', function(req, res, next) {

  var body = req.body;

  replyService.getArticleId(body.reply_id, function (articleId) {

    db.query("INSERT INTO `reply` (`reply_id`, `content`, `answer`, `user_id`, `article_id`) VALUES (?, ?, ?, ?, ?)", [
      body.reply_id,
      body.content,
      0,
      req.session.user.id * 1,
      articleId
    ], function(err, results) {
        if(err)
        {
          res.json(null, -1, "发表讨论失败")
        }
        else
        {
          articleService.adjustRank(articleId, rankScore.USER_REPLY);
          messageService.fire("replyComment", body.reply_id + "_" + results.insertId, {
            nickname: req.session.user.nickname,
            content: body.content
          });
          searchService.addReply(articleId, {
            id: results.insertId,
            content: body.content
          })
          res.json({
            id: results.insertId
          });
        }

    });

  }, function () {

    res.json(null, -1, "查询目标帖子失败");

  });

});

router.get('/reply_list/:replyId', function(req, res, next) {

  var values = [
    req.params.replyId * 1,
    req.query.startId * 1,
    req.query.len * 1
  ];

  db.query("SELECT `id`, `reply_id`, `content`, `answer`, `user_id` FROM `reply` WHERE `reply_id` = ? AND `id` " + ( req.query.sort === "asc" ? "<" : ">") + " ? ORDER BY `id` DESC LIMIT ?", values, function(err, results) {

      if(err)
      {
          res.json(null, -1, "获取评论失败");
          return;
      }

      if(results.length <= 0) {
        res.json([]);
        return;
      }

      var userLoaded = 0;

      for(var i = 0, l = results.length; i < l; ++ i) {
        var reply = results[i];
        (function (_reply) {
          db.query("SELECT `id`, `nickname`, `avatar_url` FROM `user` WHERE `id` = ?", [_reply.user_id], function (err, userResults) {

            db.query("SELECT count(`id`) as reply_count FROM `reply` WHERE `reply_id` = ?", [_reply.id], function (err, replyCountResults) {

              _reply.user = userResults[0];
              _reply.reply_count = replyCountResults[0].reply_count;
              if(++ userLoaded == l) {
                res.json(results);
              }

            });

          });
        })(reply);
      }

  });

});

module.exports = router;
